﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace AIStudio.Wpf.ECharts.Controls
{
    /// <summary>
    /// Echart.xaml 的交互逻辑
    /// </summary>
    public partial class PieEchart : UserControl
    {

        public static readonly DependencyProperty ValuesCollectionProperty = DependencyProperty.Register(
                  "ValuesCollection", typeof(ObservableCollection<PieValueClass>), typeof(PieEchart), new PropertyMetadata(null, OnValuesCollectionPropertyCallback));
        public ObservableCollection<PieValueClass> ValuesCollection
        {
            get { return (ObservableCollection<PieValueClass>)GetValue(ValuesCollectionProperty); }
            set { SetValue(ValuesCollectionProperty, value); }
        }

        private static void OnValuesCollectionPropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var chart = (PieEchart)d;
            chart.OnValuesCollectionPropertyCallback(e.NewValue as ObservableCollection<PieValueClass>, e.OldValue as ObservableCollection<PieValueClass>);
        }

        private void OnValuesCollectionPropertyCallback(ObservableCollection<PieValueClass> newvalue, ObservableCollection<PieValueClass> oldvalue)
        {
            if (oldvalue != null)
            {
                oldvalue.CollectionChanged -= PieEchart_CollectionChanged;
            }
            if (newvalue != null)
            {
                newvalue.CollectionChanged += PieEchart_CollectionChanged;
            }
            DrawPie();
        }
        private void PieEchart_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.OldItems != null)
            {
                foreach (var item in e.OldItems.OfType<PieValueClass>())
                {
                    Web.InvokeScript("jsShiftData", item.Label, item.Value);
                }
            }
            if (e.NewItems != null)
            {
                foreach (var item in e.NewItems.OfType<PieValueClass>())
                {
                    Web.InvokeScript("jsPushData", item.Label, item.Value );
                }
            }
        }

        public PieEchart()
        {
            InitializeComponent();
            Web.ObjectForScripting = new WebAdapter(Web);
            Web.Navigate(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + "Htmls\\BasicPieChart.html"));
            SizeChanged += PieEchart_SizeChanged;

            this.Loaded += PieEchart_Loaded;
        }

        private void PieEchart_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(async delegate
            {
                await Task.Delay(1000);

                Dispatcher.Invoke(() => DrawPie());
            });

        }

        private void PieEchart_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (!IsLoaded) return;

            try
            {
                Web.InvokeScript("jsSetSize", (int)(this.ActualWidth * 0.97), (int)(this.ActualHeight * 0.97));
                DrawPie();
            }
            catch { }
        }

        private void DrawPie()
        {
            try
            {
                if (!IsLoaded) return;

                if (ValuesCollection != null)
                {
                    Web.InvokeScript("jsSetDatas", Newtonsoft.Json.JsonConvert.SerializeObject(ValuesCollection.Select(p => new { name =p.Label, value=p.Value })));
                }
            }
            catch (Exception ex)
            {

            }
        }


     
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [System.Runtime.InteropServices.ComVisible(true)]//给予权限并设置可见
        public class WebAdapter
        {
            WebBrowser web;
            public WebAdapter(WebBrowser web)
            {
                this.web = web;
            }
            public void ShowMsg(string Msg)
            {
                MessageBox.Show(Msg);
            }
        }
    }


    public class PieValueClass : BindableBase
    {
        private string _label;
        public string Label
        {
            get { return _label; }
            set
            {
                if (_label != value)
                {
                    SetProperty(ref _label, value);
                }
            }
        }


        private double _value;
        public double Value
        {
            get { return _value; }
            set
            {
                if (_value != value)
                {
                    SetProperty(ref _value, value);
                }
            }
        }
    }
}
